import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import ElementPlus from 'element-plus'
import 'element-plus/lib/theme-chalk/index.css'
import './assets/css/icon.css'
import axios from 'axios'

const app = createApp(App)

app.use(ElementPlus)
    .use(store)
    .use(router)

axios.defaults.baseURL = "http://localhost:8080"
//携带cookie
// axios.defaults.withCredentials = true
//配置全局axios
app.config.globalProperties.$axios = axios;

//1 使用axios前置拦截器，让所有的请求都携带uToken
axios.interceptors.request.use(config=>{
    console.log('-----------axios前置拦截器-------------')
    //携带token
    let token =  localStorage.getItem("token");
    console.log('token---',token);
    if(token){
        config.headers['token']=token;
    }
    return config;
},error => {
    Promise.reject(error);
})

/*
//2 使用axios后置拦截器，处理没有登录请求
配置axios统一处理响应
所有axios请求得到响应都会进行以下处理
*/
axios.interceptors.response.use(res=>{
    console.log('统一处理后端返回的数据---',res,res.data.code);
    if(res.data.code == 501){
        router.push({
            path: "/login"
        });
        return Promise.reject(res.data.msg);
    }else{
        return res;
    }
    
},error=>{
    return Promise.reject(error);
})



app.mount('#app')


// app.vue写在script里面  main.js写在app挂载完之后
const debounce = (fn, delay) => {
    let timer
    return (...args) => {
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(() => {
            fn(...args)
        }, delay)
    }
}

const _ResizeObserver = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ResizeObserver{
    constructor(callback) {
        callback = debounce(callback, 200);
        super(callback);
    }
}